# certificate_manager.py
import os
import sys
import subprocess
from pathlib import Path


def get_mitmproxy_cert_path():
    """获取mitmproxy证书路径"""
    # mitmproxy的证书通常在以下位置之一
    possible_paths = [
        os.path.expanduser("~/.mitmproxy/mitmproxy-ca-cert.pem"),
        os.path.expanduser("~/.mitmproxy/mitmproxy-ca-cert.crt"),
        "/etc/ssl/certs/mitmproxy-ca-cert.pem",
    ]

    for path in possible_paths:
        print(f"🔍 尝试使用路径: {path}")
        if os.path.exists(path):
            return path
    return None


def install_certificate_linux():
    """在Linux上安装证书"""
    cert_path = get_mitmproxy_cert_path()
    if not cert_path:
        print("❌ 未找到mitmproxy证书")
        return False

    try:
        # 复制证书到系统证书目录
        subprocess.run(["sudo", "cp", cert_path, "/usr/local/share/ca-certificates/mitmproxy.crt"], check=True)
        # 更新证书存储
        subprocess.run(["sudo", "update-ca-certificates"], check=True)
        print("✅ 证书已安装到系统")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装证书失败: {e}")
        return False


def install_certificate_windows():
    """在Windows上安装证书（需要管理员权限）"""
    cert_path = get_mitmproxy_cert_path()
    if not cert_path:
        print("❌ 未找到mitmproxy证书")
        return False

    try:
        # 使用certutil安装证书到受信任的根证书颁发机构存储
        subprocess.run([
            "certutil", "-addstore", "-f", "ROOT", cert_path
        ], check=True, capture_output=True)
        print("✅ 证书已安装到Windows受信任根证书颁发机构")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装证书失败: {e}")
        return False


def install_certificate_macos():
    """在macOS上安装证书"""
    cert_path = get_mitmproxy_cert_path()
    if not cert_path:
        print("❌ 未找到mitmproxy证书")
        return False

    try:
        # 添加到系统钥匙串
        subprocess.run([
            "sudo", "security", "add-trusted-cert", "-d", "-r", "trustRoot",
            "-k", "/Library/Keychains/System.keychain", cert_path
        ], check=True)
        print("✅ 证书已安装到macOS系统钥匙串")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装证书失败: {e}")
        return False


def print_manual_install_instructions():
    """打印手动安装说明"""
    cert_path = get_mitmproxy_cert_path()
    if cert_path:
        print(f"📄 mitmproxy证书路径: {cert_path}")
    else:
        print("📄 启动mitmproxy后，证书将生成在 ~/.mitmproxy/ 目录下")

    instructions = """
💻 手动安装证书指南:

1. 启动mitmproxy后，访问 http://mitm.it/
   - 点击相应的操作系统图标下载证书

2. Windows:
   - 双击下载的证书文件
   - 选择"安装证书"
   - 选择"本地计算机"
   - 选择"将所有的证书都放入下列存储"
   - 点击"浏览"，选择"受信任的根证书颁发机构"
   - 完成安装

3. macOS:
   - 双击证书文件
   - 在钥匙串访问中，将证书拖拽到"系统"钥匙串
   - 双击证书，展开"信任"部分
   - 设置"使用此证书时"为"始终信任"

4. Linux (Ubuntu/Debian):
   - sudo cp mitmproxy-ca-cert.pem /usr/local/share/ca-certificates/
   - sudo update-ca-certificates

5. 浏览器特定设置:
   - Chrome/Chromium: 设置 -> 隐私设置和安全性 -> 安全 -> 管理设备证书
   - Firefox: 设置 -> 隐私与安全 -> 证书 -> 查看证书 -> 证书颁发机构 -> 导入
    """
    print(instructions)


def main():
    """主函数"""
    print("🔐 mitmproxy证书管理工具")
    print("=" * 40)

    # 显示证书信息
    cert_path = get_mitmproxy_cert_path()
    if cert_path:
        print(f"✅ 找到mitmproxy证书: {cert_path}")
    else:
        print("⚠️ 未找到mitmproxy证书")
        print("💡 请先启动mitmproxy以生成证书")

    print("\n选择操作:")
    print("1. 显示手动安装说明")
    print("2. 自动安装证书 (需要管理员权限)")

    try:
        choice = input("请输入选项 (1-2): ").strip()

        if choice == "1":
            print_manual_install_instructions()
        elif choice == "2":
            if sys.platform.startswith("linux"):
                install_certificate_linux()
            elif sys.platform.startswith("win"):
                install_certificate_windows()
            elif sys.platform.startswith("darwin"):
                install_certificate_macos()
            else:
                print("❌ 不支持的操作系统")
                print_manual_install_instructions()
        else:
            print("❌ 无效选项")
            print_manual_install_instructions()

    except KeyboardInterrupt:
        print("\n👋 操作已取消")


if __name__ == "__main__":
    main()
